#include "ArgParser.h"
#include "types.h"
#include <stdio.h>
#include <stdlib.h>
ArgParser::ArgParser(int argc, char *argv[]) {
	ParseBoolArgs(argc, argv);
	ParseFileArgs(argc, argv);
	ParseStringArgs(argc, argv);
}

void ArgParser::ParseBoolArgs(int argc, char *argv[]) {
	S32 i;
	for(i = 1; i < argc; ++i) {
		S32 nLen = strlen(argv[i]);
		if (nLen < 3 || argv[i][0] != '-' || argv[i][1] != '-' || argv[i][2] == '=') continue;
		S32 j;
		for(j = 2; j < nLen; j++) 
			if (argv[i][j] == '=') continue;
		m_mapBoolArgs[std::string(argv[i] + 2)] = true;
	}
}

void ArgParser::ParseFileArgs(int argc, char *argv[]) {
	S32 i;
	for(i = 1; i < argc; ++i) {
		S32 nLen = strlen(argv[i]);
		if (nLen < 1 || argv[i][0] == '-') 
			continue;
		m_setFileArgs.insert(std::string(argv[i]));
	}
}

void ArgParser::ParseStringArgs(int argc, char *argv[]) {
	S32 i;
	for(i = 1; i < argc; ++i) {
		S32 nLen = strlen(argv[i]);
		if (nLen < 3 || argv[i][0] != '-' || argv[i][1] != '-' || argv[i][2] == '=') continue;
		S32 j;
		for(j = 2; j < nLen; ++j)
			if (argv[i][j] == '=') 
				break;
		if (j == nLen || j == nLen - 1) continue;
		std::string strKey, strValue;
		strKey.assign(argv[i] + 2, j - 2);
		strValue.assign(argv[i] + j + 1);
		m_mapStringArgs[strKey] = strValue;
	}
}

bool ArgParser::IsSomething(const char *sz) const {
	std::string str(sz);
	BoolIter iter;
	return (iter = m_mapBoolArgs.find(str)) != m_mapBoolArgs.end() &&
	       iter->second;
}

const char * ArgParser::GetSomethingString(const char *sz) const {
	std::string str(sz);
	StringIter iter;
	return (iter = m_mapStringArgs.find(str)) != m_mapStringArgs.end() ?
	        iter->second.c_str() : NULL;
}

S32 ArgParser::GetSomethingS32(const char *szKey, S32 nDefault) const {
	const char *szValue = GetSomethingString(szKey);
	if (!szValue) 
		return nDefault;
	S32 nRet;
	if (sscanf(szValue, "%ld", &nRet))
		return nRet;
	else
		return nDefault;
}
